/*    Copyright 2010 Tobias Marschall
 *
 *    This file is part of MoSDi.
 *
 *    MoSDi is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    MoSDi is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with MoSDi.  If not, see <http://www.gnu.org/licenses/>.
 */

package mosdi.util.iterators;

import java.util.Arrays;
import java.util.NoSuchElementException;

import mosdi.util.ProductEncoder;

/** Iterator that returns all strings of a given length. */
public class StringIterator implements LexicographicalIterator {

	private int length;
	private int alphabetSize;
	private ProductEncoder encoder;
	private int next;
	private int[] current;
	
	public StringIterator(int alphabetSize, int length) {
		this.length = length;
		this.alphabetSize = alphabetSize;
		int[] bases = new int[length];
		Arrays.fill(bases, alphabetSize);
		encoder = new ProductEncoder(false, bases);
		next = 0;
		current = null;
	}
	
	@Override
	public int getLeftmostChangedPosition() {
		if (current==null) throw new IllegalStateException();
		int result = length-1;
		while ((result>0) && (current[result]==0)) result-=1;
		return result;
	}

	@Override
	public int getStringLength() {
		return length;
	}

	@Override
	public int[] peek() {
		if (next>=encoder.getValueCount()) throw new NoSuchElementException();
		return encoder.decode(next);
	}

	@Override
	public void skip(int position) {
		int[] a = Arrays.copyOf(current, length);
		for (int i=position+1; i<length; ++i) {
			a[i] = alphabetSize-1; 
		}
		next = encoder.encode(a)+1;
	}

	@Override
	public boolean hasNext() {
		return next<encoder.getValueCount();
	}

	@Override
	public int[] next() {
		try {
			current = encoder.decode(next);
			next += 1;
			return current;
		} catch (IllegalArgumentException e) {
			throw new NoSuchElementException();
		}
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException();
	}

}
